package _interview100;

/**
 * 189. 轮转数组
 */
public class No189 {
    /**
     * 1. 数组翻转
     */
    public void rotate1(int[] nums, int k) {
        int n = nums.length;
        k %= n;
        reverse(nums, 0, n - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, n - 1);
    }

    private void reverse(int[] nums, int left, int right) {
        while (left < right) {
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++;
            right--;
        }
    }

    /**
     * 2. 使用额外的数组
     */
    public void rotate2(int[] nums, int k) {
        int n = nums.length;
        int[] tempArr = new int[n];
        for (int i = 0; i < tempArr.length; i++) {
            tempArr[(i + k) % n] = nums[i];
        }
        System.arraycopy(tempArr, 0, nums, 0, n);
    }
}
